package cn.gaily.eduservice.listener;

import cn.gaily.eduservice.entity.EduSubject;
import cn.gaily.eduservice.entity.excel.SubjectData;
import cn.gaily.eduservice.service.EduSubjectService;
import cn.gaily.servicebase.exceptionhandler.GuliException;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import java.util.Map;

public class SubjectExcelListener extends AnalysisEventListener<SubjectData> {

    public EduSubjectService eduSubjectService;
    public SubjectExcelListener(){}
    public SubjectExcelListener(EduSubjectService eduSubjectService){
        this.eduSubjectService = eduSubjectService;
    }
    /**
     * When analysis one row trigger invoke function.
     *
     * @param data    one row value. Is is same as {@link AnalysisContext#readRowHolder()}
     * @param context
     */
    @Override
    public void invoke(SubjectData data, AnalysisContext context) {
        if(data == null){
            throw new GuliException(20001,"excel文件数据为空");
        }
        //没有相同的一级分类，则新增一级分类
        EduSubject oneSubject = existOneSubject(eduSubjectService, data.getFirstSubjectName());
        if(oneSubject == null){
            oneSubject = new EduSubject();
            oneSubject.setParentId("0");
            oneSubject.setTitle(data.getFirstSubjectName());
            eduSubjectService.save(oneSubject);
        }
        String pid = oneSubject.getId();

        //添加二级分类
        EduSubject twoSubject = existTwoSubject(eduSubjectService, data.getSecondSubjectName(), pid);
        if(twoSubject == null){
            twoSubject = new EduSubject();
            twoSubject.setParentId(pid);
            twoSubject.setTitle(data.getSecondSubjectName());
            eduSubjectService.save(twoSubject);
        }

    }
    //判断一级分类不能重复添加方法
    private EduSubject existOneSubject(EduSubjectService eduSubjectService,String name){
        QueryWrapper<EduSubject> wrapper = new QueryWrapper<>();
        wrapper.eq("title",name);
        wrapper.eq("parent_id","0");
        return eduSubjectService.getOne(wrapper);
    }
    //判断二级分类不能重复添加方法
    private EduSubject existTwoSubject(EduSubjectService eduSubjectService,String name,String pid){
        QueryWrapper<EduSubject> wrapper = new QueryWrapper<>();
        wrapper.eq("title",name);
        wrapper.eq("parent_id",pid);
        return eduSubjectService.getOne(wrapper);
    }

    /**
     * Returns the header as a map.Override the current method to receive header data.
     *
     * @param headMap
     * @param context
     */
    @Override
    public void invokeHeadMap(Map<Integer, String> headMap, AnalysisContext context) {
        System.out.println(headMap);
    }


    /**
     * if have something to do after all analysis
     *
     * @param context
     */
    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {

    }
}
